<!DOCTYPE html>
<html>
<head>
<title>WebSocket 例子: 反转</title>
<style type="text/css">
#connect-container {
	float: left;
	width: 400px
}

#connect-container div {
	padding: 5px;
}

#console-container {
	float: left;
	margin-left: 15px;
	width: 400px;
}

#console {
	border: 1px solid #CCCCCC;
	border-right-color: #999999;
	border-bottom-color: #999999;
	height: 170px;
	overflow-y: scroll;
	padding: 5px;
	width: 100%;
}

#console p {
	padding: 0;
	margin: 0;
}
</style>
<script type="text/javascript">
	//var ws = new SockJS(url, undefined, {protocols_whitelist: transports}) ；   //初始化 websocket  
	var ws = null;

	function setConnected(connected) {
		document.getElementById('connect').disabled = connected;
		document.getElementById('disconnect').disabled = !connected;
		document.getElementById('reverse').disabled = !connected;
	}

	function connect() {
		var target = document.getElementById('target').value;
		ws = new WebSocket(target);
		ws.onopen = function() {
			setConnected(true);
			log('链接已建立!!');
		};
		ws.onmessage = function(event) {
			log('接收: ' + event.data);
		};
		ws.onclose = function() {
			setConnected(false);
			log('链接已关闭!!');
		};
	}

	function updateTarget() {
		if (window.location.protocol == 'http:') {
			document.getElementById('target').value = 'ws://'
					+ window.location.host
					+ document.getElementById('target').value;
		} else {
			document.getElementById('target').value = 'wss://'
					+ window.location.host
					+ document.getElementById('target').value;
		}
	}

	function disconnect() {
		if (ws != null) {
			ws.close();
			ws = null;
		}
		setConnected(false);
	}

	function reverse() {
		if (ws != null) {
			var message = document.getElementById('message').value;
			log('Sent: ' + message);
			ws.send(message);
		} else {
			alert('链接还没有建立,请先建立链接!');
		}
	}

	function log(message) {
		var console = document.getElementById('console');
		var p = document.createElement('p');
		p.style.wordWrap = 'break-word';
		p.appendChild(document.createTextNode(message));
		console.appendChild(p);
		while (console.childNodes.length > 25) {
			console.removeChild(console.firstChild);
		}
		console.scrollTop = console.scrollHeight;
	}
</script>
</head>
<body onload="updateTarget()">
	<noscript>
		<h2 style="color: #ff0000">检查你的浏览器是否支持socketjs</h2>
	</noscript>
	<div>
		<div id="connect-container">
			<div>
				<input id="target" type="text" size="40" style="width: 350px"
					value="/reverse" />
			</div>
			<div>
				<button id="connect" onclick="connect();">点击链接</button>
				<button id="disconnect" disabled="disabled" onclick="disconnect();">点击断开</button>
			</div>
			<div>
				<textarea id="message" style="width: 350px">测试信息!!!</textarea>
			</div>
			<div>
				<button id="reverse" onclick="reverse();" disabled="disabled">消息反转</button>
			</div>
		</div>
		<div id="console-container">
			<div id="console"></div>
		</div>
	</div>
</body>
</html>
